package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.common.constant.ProductInfo;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.atguigu.gulimall.product.vo.ReturnArrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveArrInfo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 插入数据后，自动返回主键
        this.save(attrEntity);
        if (attr.getAttrType() != ProductInfo.AttrProductEnum.PRODUCT_ATTR_SALE.getCode() && attr.getAttrGroupId() != null) {
            // 设置关联关系表中的信息
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrgroupRelationEntity);
        }
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String attrtype) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type", attrtype.equalsIgnoreCase("sale") ? ProductInfo.AttrProductEnum.PRODUCT_ATTR_SALE.getCode() : ProductInfo.AttrProductEnum.PRODUCT_ATTR_BASE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);

            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> attrEntityList = page.getRecords();
        List<ReturnArrVo> list = attrEntityList.stream().map((item) -> {
            // 设置分组名和分类名
            ReturnArrVo returnArrVo = new ReturnArrVo();
            BeanUtils.copyProperties(item, returnArrVo);
            Long attrId = item.getAttrId();
            if (!attrtype.equalsIgnoreCase("sale")) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
                if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        returnArrVo.setGroupName(attrGroupEntity.getAttrGroupName());

                    }
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
            if (categoryEntity != null) {
                returnArrVo.setCatelogName(categoryEntity.getName());
            }
            return returnArrVo;
        }).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;
    }

    /**
     * 获取当前属性的详情信息
     *
     * @param attrId
     * @return
     */
    @Override
    public ReturnArrVo getDetail(Long attrId) {
        ReturnArrVo returnArrVo = new ReturnArrVo();
        AttrEntity attrEntity = getById(attrId);
        BeanUtils.copyProperties(attrEntity, returnArrVo);
        if (ProductInfo.AttrProductEnum.PRODUCT_ATTR_SALE.getCode() != returnArrVo.getAttrType()) {
            AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attrgroupRelationEntity != null) {
                if (attrgroupRelationEntity.getAttrGroupId() != null) {
                    returnArrVo.setAttrGroupId(attrgroupRelationEntity.getAttrGroupId());
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        returnArrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
        }
        Long[] catelogPath = categoryService.getCatelogPath(returnArrVo.getCatelogId());
        returnArrVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(returnArrVo.getCatelogId());
        if (categoryEntity != null) {
            returnArrVo.setCatelogName(categoryEntity.getName());
        }
        return returnArrVo;

    }

    @Transactional
    @Override
    public void updateDetail(AttrVo attr) {
        // 修改基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attr.getAttrType() != ProductInfo.AttrProductEnum.PRODUCT_ATTR_SALE.getCode()) {
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            Long attrGroupId = attr.getAttrGroupId();
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrGroupId);
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            if (count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else if (count <= 0 && attrAttrgroupRelationEntity.getAttrGroupId() != null){
                // 新增
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }


    }

    /**
     * 获取当前分组下关联的属性信息
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getGroupAttrRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<AttrEntity> list = null;
        if (attrAttrgroupRelationEntities != null && attrAttrgroupRelationEntities.size() > 0) {
            List<Long> attrIds = attrAttrgroupRelationEntities.stream().map((attr) -> {
                return attr.getAttrId();
            }).collect(Collectors.toList());
            list = this.listByIds(attrIds);
        }
        return list;
    }

    @Override
    public void deleteGroupAttrRelation(List<AttrGroupVo> attrGroupVos) {
        if (attrGroupVos != null && attrGroupVos.size() > 0) {
            attrAttrgroupRelationDao.deleteGroupAttrRelation(attrGroupVos);
        }
    }

    @Override
    public PageUtils getNoGroupArrRelation(Map<String, Object> params, Long attrgroupId) {

        // 获取当前分组下的分类id,并查询分类下的所有属性信息
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId(); // 当前分类id
        // 获取其他分组下关联的所有属性
        // 1、获取当前分类下关联的分组信息（除去自身）
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> attrGroupIds = attrGroupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        // 2、获取其他分组下关联的所有属性信息
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
        List<Long> attrIds = attrgroupRelationEntities.stream().map((attrRelationGroup) -> {
            return attrRelationGroup.getAttrId();
        }).collect(Collectors.toList());
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductInfo.AttrProductEnum.PRODUCT_ATTR_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0) {
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 3、剔除所有属性中，其他分组包含的属性信息
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }
}